package com.softeem.god.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.god.comm.R;
import com.softeem.god.entity.Blacklist;
import com.softeem.god.service.BlacklistService;
import com.softeem.god.service.UserService;
import com.softeem.god.utils.BlacklistDataGenerator;
import com.softeem.god.utils.GenerateBlacklistData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "黑名单管理", description = "黑名单管理接口")
@RestController
@RequestMapping("/blacklist")
public class BlacklistController {

    @Autowired
    private BlacklistService blacklistService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private GenerateBlacklistData generateBlacklistData;

    @Operation(summary = "黑名单列表", description = "根据提供的页码和数据条数实现分页查询")
    @Parameters({
            @Parameter(name = "page", description = "页码"),
            @Parameter(name = "limit", description = "数据条数"),
            @Parameter(name = "username", description = "用户名")
    })
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public R list(@RequestParam(defaultValue = "1") Integer page, 
                  @RequestParam(defaultValue = "5") Integer limit,
                  @RequestParam(required = false) String username) {
        // 创建分页对象
        Page<Blacklist> iPage = new Page<>(page, limit);
        
        // 创建查询条件
        QueryWrapper<Blacklist> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            // 关联查询用户表获取用户名
            queryWrapper.like("u.username", username);
        }
        
        // 执行查询(分页)
        IPage<Blacklist> result = blacklistService.selectBlacklistWithUser(iPage, queryWrapper);
        long count = blacklistService.count(queryWrapper);
        // 返回结果
        return R.success().setData(result).setCount(count);
    }

    @Operation(summary = "添加到黑名单", description = "将用户添加到黑名单")
    @PostMapping("/add")
    public R add(@RequestBody Blacklist blacklist) {
        // 设置创建时间
        blacklist.setCreateTime(new Date());
        // 保存到数据库
        boolean result = blacklistService.save(blacklist);
        return result ? R.success().setMsg("添加成功") : R.error().setMsg("添加失败");
    }

    @Operation(summary = "从黑名单移除", description = "根据ID从黑名单移除用户")
    @Parameters({
            @Parameter(name = "id", description = "黑名单ID")
    })
    @DeleteMapping("/delete")
    public R delete(@RequestParam Integer id) {
        boolean result = blacklistService.removeById(id);
        return result ? R.success().setMsg("移除成功") : R.error().setMsg("移除失败");
    }

    @Operation(summary = "检查用户是否在黑名单中", description = "根据用户ID检查是否在黑名单中")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID")
    })
    @GetMapping("/check")
    public R check(@RequestParam Integer userId) {
        QueryWrapper<Blacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Blacklist blacklist = blacklistService.getOne(queryWrapper);
        return blacklist != null ? R.success().setData(true).setMsg("用户在黑名单中") : R.success().setData(false).setMsg("用户不在黑名单中");
    }
    
    @Operation(summary = "批量添加黑名单数据", description = "随机生成并添加指定数量的黑名单数据")
    @Parameters({
            @Parameter(name = "count", description = "添加数量"),
            @Parameter(name = "userIds", description = "用户ID列表")
    })
    @PostMapping("/batchAdd")
    public R batchAdd(@RequestParam(defaultValue = "10") Integer count,
                      @RequestBody List<Integer> userIds) {
        try {
            // 生成随机黑名单数据
            List<Blacklist> blacklists = BlacklistDataGenerator.generateRandomBlacklists(userIds, count);
            
            // 批量保存到数据库
            boolean result = blacklistService.saveBatch(blacklists);
            
            return result ? R.success().setMsg("批量添加成功，共添加" + blacklists.size() + "条记录") : R.error().setMsg("批量添加失败");
        } catch (Exception e) {
            return R.error().setMsg("批量添加异常：" + e.getMessage());
        }
    }
    
    @Operation(summary = "自动生成黑名单数据", description = "随机生成并添加指定数量的黑名单数据（从现有用户中随机选择）")
    @Parameters({
            @Parameter(name = "count", description = "生成数量")
    })
    @PostMapping("/generate")
    public R generate(@RequestParam(defaultValue = "10") Integer count) {
        try {
            String result = generateBlacklistData.generateRandomBlacklists(count);
            return R.success().setMsg(result);
        } catch (Exception e) {
            return R.error().setMsg("生成黑名单数据异常：" + e.getMessage());
        }
    }
    
    @Operation(summary = "根据用户ID查询黑名单记录", description = "根据用户ID查询该用户的所有黑名单记录")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID")
    })
    @GetMapping("/listByUserId")
    public R listByUserId(@RequestParam Integer userId) {
        try {
            List<Blacklist> blacklistRecords = blacklistService.selectByUserId(userId);
            return R.success().setData(blacklistRecords);
        } catch (Exception e) {
            return R.error().setMsg("查询黑名单记录异常：" + e.getMessage());
        }
    }
}